var express = require('express')
var router = express.Router()
const ExcelJS = require('exceljs');
const app = express();
// 允许文件下载
app.use(express.static('exports'));
// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
    console.log('Time: ', Date.now())
    //模块路由中检测是否携带了 token
    if (!req.auth) {
        return res.send({
            status: 403,
            message: "缺少token"
        });
    }
    next()
})
//  从db文件中导入的数据库模块
var db = require("../db/mysql");
const { json } = require('body-parser');

// 人员表操作——添加
router.post('/ueses_add', (req, res) => {
    // 先获取用户的请求数据，存到变量“body”中
    var body = req.body
    // 用结构复制把用户请求数据里面的的“uname,part,mobile, pwd”分别拿出来，方便接下来向数据库中添加数据时使用
    let { uname, part, mobile, pwd } = body
    db.query('SELECT * FROM users where account = ?', [mobile], function (error, results) {
        if (results.length > 0) {
            // res.send('此手机号已经存在用户')
            res.send({ data: [], code: 1, msg: "此手机号已经存在用户" }) //标准返回信息
        } else {
            db.query(
                'INSERT INTO users (uname,utype,account,pwd) VALUES (?,?,?,?)',
                [uname, part, mobile, pwd],
                function (err, results) {
                    //  响应数据
                    if (err) {
                        res.json({ code: 1, msg: "操作失败", data: { err } })
                    } else {
                        res.json({ code: 0, msg: "添加完成", data: { uname: uname, DEPARTMENTt: part, mobile: mobile, password: pwd } })
                    }
                    console.log(err + 'ok了!')
                });
        }
    })
})
// 人员表操作——删除
router.get('/users_delete/:id', (req, res) => {
    console.log(req.params.id)
    db.query('DELETE FROM users WHERE id = ?', [parseInt(req.params.id)],
        function (error, result) {
            if (error) {
                res.json({ code: 1, msg: "删除失败", data: { err } })
            } else {
                res.json({ code: 0, msg: "删除成功" })
            }
        }
    )
})
// 人员表操作——多个人员的删除、
router.get('/users_deletes/:id', (req, res) => {
    console.log(req.params.id)
    let userids = req.params.id
    let useridps = JSON.parse(userids)
    let tiaojian = 'DELETE FROM users WHERE id IN (?)';
    db.query(tiaojian, [useridps], function (error, result) {
        if (error) {
            res.json({ code: 1, msg: "删除失败", data: { error: error } });
        } else {
            res.json({ code: 0, msg: "删除成功", data: { affectedRows: result.affectedRows } });
        }
    });
})
// 人员表操作——查找列表
router.get('/users_list', (req, res) => {
    // 获取token
    console.log(req.auth)  //获取token中信息:{ uid: 9, account: '15527098790', iat: 1721979755, exp: 1722238955 }
    let uid = req.auth.uid;
    // 获取url中的参数 ?page=1&page_size=3,参数放在req.query中 { page: '1', page_size: '3' }
    let { page, page_size } = req.query;
    // 查询limit
    let start = (page - 1) * page_size;
    let limit = ` limit ${start}, ${page_size}` //limit 0,3
    let selectSQL = `
    SELECT a.id,a.uname,a.utype,a.account,b.pname 
    FROM users as a 
    left join department as b
    on a.utype = b.id 
    ORDER BY a.id DESC
    ${limit}`;
    db.query(selectSQL, function (error, results) {
        if (error) console.log(error)
        var id;
        var uname;
        var part;
        var mobile;
        var pwd;
        var part_name;
        let arr = [];
        for (let i = 0; i < results.length; i++) {
            id = results[i].id
            uname = results[i].uname
            part = results[i].utype
            mobile = results[i].account
            pwd = results[i].pwd
            part_name = results[i].pname
            arr.push({ id, uname, part, mobile, pwd, part_name })
            console.log(part)
        }
        //总条数
        db.query("SELECT count(id) as total FROM users", (err, data) => {
            console.log("total:", data)
            let totalNum = data[0]?.total
            res.json({ code: 0, msg: "信息详情", data: { list: arr, totalNum } })
        })
    })
})
// 人员表操作——查找搜索
router.get("/users_search", (req, res) => {
    console.log(req.query, res.params)
    let { uname, account, utype } = req.query;

    // 根据搜索的内容不同，生成查询条件
    let where = `WHERE 1 = 1 `
    if (uname) {
        where += `AND a.uname LIKE '%${uname}%' `
    }

    if (account) {
        where += `AND a.account LIKE '%${account}%' `
    }

    if (utype) {
        where += `AND a.utype LIKE '%${utype}%' `
    }
    // sql
    let selectSQL = `SELECT a.id,a.uname,a.utype,a.account,b.pname 
    FROM users AS a 
    LEFT JOIN department AS b 
    ON a.utype = b.id 
    ${where}`;
    db.query(selectSQL, function (error, results) {
        console.log(error, results)
        var id;
        var uname;
        var part;
        var mobile;
        var pwd;
        var part_name;
        let arr = [];
        for (let i = 0; i < results.length; i++) {
            id = results[i].id
            uname = results[i].uname
            part = results[i].utype
            mobile = results[i].account
            pwd = results[i].pwd
            part_name = results[i].pname

            arr.push({ id, uname, part, mobile, pwd, part_name })
            console.log(part)
        }

        // let rows = results;
        res.json({ code: 0, msg: "信息详情", data: arr })
    })
})
// 人员表操作——修改-获取数据
router.get('/users_users_edit/:id', (req, res) => {
    console.log(req.query, req.params)
    // 、！！！ get 取参数
    //  ?page=1&page_size=3,参数放在请求字符客户，问号开头的，req.query中 { page: '1', page_size: '3' }取
    //  /renyuan/edit/5 ,参数是动态路由 （/edit/:id），req.param中取参数 { id: '5' } 取
    if (!req.params.id) {
        res.send({ code: 1, msg: '缺少参数', data: [] });
    }
    let selectSQL = `
    SELECT a.id,a.uname,a.utype,a.account,a.pwd,b.pname 
    FROM users as a 
    left join department as b 
    on a.utype = b.id
    WHERE a.id=?
    `;
    db.query(selectSQL, [parseInt(req.params.id)],
        function (error, results) {
            /*
            this.xiugaiobtainuid = response.data.id;
          this.edutruleForm.unamesave = response.data.uname;
          this.edutruleForm.umobilesave = response.data.account;
          this.edutruleForm.upartsave = response.data.pname;
          this.edutruleForm.upwdsave = response.data.pwd;
            */
            var id;
            var uname;
            var account;
            var pwd;
            var pname;
            var arr = [];
            for (let i = 0; i < results.length; i++) {
                id = results[i].id
                uname = results[i].uname
                account = results[i].account
                pwd = results[i].pwd
                pname = results[i].pname

                arr.push({ id, uname, account, pwd, pname })
            }
            // 响应数据 ,扁平化数组 Array.flat(1)
            res.send({ code: 0, msg: '查询数据', data: arr });
        }
    );
})
// 人员表操作——修改-保存数据
router.post('/users_save_edit/:id', (req, res) => {
    // 声明body
    let id = req.params.id; //动态路由中的参数通过params取
    let { uname, part, mobile, pwd } = req.body; //普通提交的数据，在req.body中取到
    // 执行sql语句
    db.query('UPDATE users SET uname=?,utype=?,account=?,pwd=? WHERE id=?',
        [uname, part, mobile, pwd, id], function () {
            // 响应信息
            res.json({ msg: "修改完毕", code: 0, data: { uname, part, mobile, id } })
        })
    // res.json({ msg: "人员修改", code: 1, data: [] })
})
// 角色表操作——添加
router.post('/roles_add', (req, res) => {
    // 先获取用户的请求数据，存到变量“body”中
    var body = req.body
    // 用结构复制把用户请求数据里面的的“uname,part,mobile, pwd”分别拿出来，方便接下来向数据库中添加数据时使用
    let { name, description, created_at, updated_at } = body
    db.query('SELECT * FROM roles where name = ?', [name], function (error, results) {
        if (results.length > 0) {
            // res.send('此手机号已经存在用户')
            res.send({ data: [], code: 1, msg: "此角色名已经存在！" }) //标准返回信息
        } else {
            db.query(
                'INSERT INTO roles (name,description,created_at,updated_at) VALUES (?,?,?,?)',
                [name, description, created_at, updated_at],
                function (err, results) {
                    //  响应数据
                    if (err) {
                        res.json({ code: 1, msg: "操作失败", data: { err } })
                    } else {
                        res.json({ code: 0, msg: "添加完成", data: { name: name, description: description, created_at: created_at, updated_at: updated_at } })
                    }
                    console.log(err + 'ok了!')
                });
        }
    })
    // res.json({ msg: "人员添加", code: 1, data: [] })
})
// 角色表操作——删除
router.get('/roles_delete/:id', (req, res) => {
    console.log(req.params.id)
    db.query('DELETE FROM roles WHERE id = ?', [parseInt(req.params.id)],
        function (error, result) {
            if (error) {
                res.json({ code: 1, msg: "删除失败", data: { err } })
            } else {
                res.json({ code: 0, msg: "删除成功" })
            }
        }
    )
})
// 角色表操作——多个删除
router.get('/roles_deletes/:id', (req, res) => {
    console.log(req.params.id)
    let userids = req.params.id
    let useridps = JSON.parse(userids)
    let tiaojian = 'DELETE FROM roles WHERE id IN (?)';
    db.query(tiaojian, [useridps], function (error, result) {
        if (error) {
            res.json({ code: 1, msg: "删除失败", data: { error: error } });
        } else {
            res.json({ code: 0, msg: "删除成功", data: { affectedRows: result.affectedRows } });
        }
    });
})
// 角色表操作——查找列表
router.get('/roles_list', (req, res) => {
    // 获取token
    console.log(req.auth)  //获取token中信息:{ uid: 9, account: '15527098790', iat: 1721979755, exp: 1722238955 }
    let uid = req.auth.uid;
    // 获取url中的参数 ?page=1&page_size=3,参数放在req.query中 { page: '1', page_size: '3' }
    let { page, page_size } = req.query;
    // 查询limit
    let start = (page - 1) * page_size;
    let limit = ` limit ${start}, ${page_size}` //limit 0,3
    let selectSQL = `
    SELECT id,name,description,created_at,updated_at 
    FROM roles 
    ORDER BY id DESC
    ${limit}`;
    db.query(selectSQL, function (error, results) {
        if (error) console.log(error)
        var id;
        var name;
        var description;
        var created_at;
        var updated_at;
        let arr = [];
        for (let i = 0; i < results.length; i++) {
            id = results[i].id
            name = results[i].name
            description = results[i].description
            created_at = results[i].account
            updated_at = results[i].updated_at
            arr.push({ id, name, description, created_at, updated_at })
        }
        //总条数
        db.query("SELECT count(id) as total FROM roles", (err, data) => {
            console.log("total:", data)
            let totalNum = data[0]?.total
            res.json({ code: 0, msg: "信息详情", data: { list: arr, totalNum } })
        })
    })
})
// 角色表操作——查找搜索
router.get("/roles_search", (req, res) => {
    let { name, description, created_at, updated_at, page, page_size } = req.query;
    // 查询limit
    let start = (page - 1) * page_size;
    let limit = ` LIMIT ${start}, ${page_size}`; // limit 0,10

    let whereConditions = ['1 = 1']; // 使用数组来收集条件，避免字符串拼接的复杂性

    // 对 name 进行模糊查询
    if (name) {
        whereConditions.push(`name LIKE ?`); // 使用参数化查询防止 SQL 注入
    }

    // 对 description 进行模糊查询
    if (description) {
        whereConditions.push(`description LIKE ?`);
    }

    // 对 created_at 进行查询，假设用户输入的是一个日期范围，例如 '2024-01-01 - 2024-01-31'
    if (created_at) {
        // 这里需要根据实际输入格式进行解析和处理
        whereConditions.push(`created_at BETWEEN ? AND ?`);
    }

    // 对 updated_at 进行查询，同上
    if (updated_at) {
        // 这里需要根据实际输入格式进行解析和处理
        whereConditions.push(`updated_at BETWEEN ? AND ?`);
    }

    let whereClause = whereConditions.join(' AND '); // 将条件组合成一个字符串
    let selectSQL = `SELECT id, name, description, created_at, updated_at FROM roles WHERE ${whereClause} ${limit}`;

    let countSQL = `SELECT COUNT(*) AS total FROM roles WHERE ${whereClause}`; // 计算总数的SQL查询语句

    let queryParams = [];
    if (name) queryParams.push(`%${name}%`);
    if (description) queryParams.push(`%${description}%`);
    if (created_at) {
        let dates = created_at.split(' - ').map(date => date.trim());
        queryParams.push(dates[0], dates[1]);
    }
    if (updated_at) {
        let dates = updated_at.split(' - ').map(date => date.trim());
        queryParams.push(dates[0], dates[1]);
    }

    // 先执行总数查询
    db.query(countSQL, queryParams, (error, countResults) => {
        if (error) {
            console.error(error);
            return res.status(500).json({ code: 1, msg: "数据库查询错误" });
        }
        let total = countResults[0].total; // 获取总数

        // 再执行分页查询
        db.query(selectSQL, queryParams, (error, results) => { // 使用参数化查询
            if (error) {
                console.error(error);
                return res.status(500).json({ code: 1, msg: "数据库查询错误" });
            }
            console.log(selectSQL);
            let arr = results.map(row => ({
                id: row.id,
                name: row.name,
                description: row.description,
                created_at: row.created_at,
                updated_at: row.updated_at
            }));

            // 返回分页数据和总数
            res.json({
                code: 0,
                msg: "角色搜索详情",
                data: arr,
                total: total
            });
        });
    });
});
// 角色表操作——修改-获取数据
router.get('/roles_users_edit/:id', (req, res) => {
    console.log(req.query, req.params)
    // 、！！！ get 取参数
    //  ?page=1&page_size=3,参数放在请求字符客户，问号开头的，req.query中 { page: '1', page_size: '3' }取
    //  /renyuan/edit/5 ,参数是动态路由 （/edit/:id），req.param中取参数 { id: '5' } 取
    // name, description, created_at, updated_at
    if (!req.params.id) {
        res.send({ code: 1, msg: '缺少参数', data: [] });
    }
    let selectSQL = `
    SELECT id,name,description,created_at,updated_at
    FROM roles WHERE id=?
    `;
    db.query(selectSQL, [parseInt(req.params.id)],
        function (error, results) {
            var id;
            var name;
            var description;
            var created_at;
            var updated_at;
            var arr = [];
            for (let i = 0; i < results.length; i++) {
                id = results[i].id
                name = results[i].name
                description = results[i].description
                created_at = results[i].created_at
                updated_at = results[i].updated_at
                arr.push({ id, name, description, created_at, updated_at })
            }
            // 响应数据 ,扁平化数组 Array.flat(1)
            res.send({ code: 0, msg: '查询数据', data: arr });
        }
    );
})
// 角色表操作——修改-保存数据
router.post('/roles_save_edit/:id', (req, res) => {
    // 声明body
    let id = req.params.id; //动态路由中的参数通过params取
    let { name, description, created_at, updated_at } = req.body; //普通提交的数据，在req.body中取到
    // 执行sql语句
    // name, description, created_at, updated_at
    db.query('UPDATE roles SET name=?,description=?,created_at=?,updated_at=? WHERE id=?',
        [name, description, created_at, updated_at, id], function () {
            // 响应信息
            res.json({ msg: "修改完毕", code: 0, data: { name, description, created_at, updated_at, id } })
        })
    // res.json({ msg: "人员修改", code: 1, data: [] })
})
// 权限（permissions）表操作——添加
router.post('/permissions_add', (req, res) => {
    // 先获取用户的请求数据，存到变量“body”中
    var body = req.body
    // 用结构复制把用户请求数据里面的的“uname,part,mobile, pwd”分别拿出来，方便接下来向数据库中添加数据时使用
    let { name, description, level, father } = body
    db.query('SELECT * FROM permissions where name = ?', [name], function (error, results) {
        if (results.length > 0) {
            // res.send('此手机号已经存在用户')
            res.send({ data: [], code: 1, msg: "此角色名已经存在！" }) //标准返回信息
        } else {
            db.query(
                'INSERT INTO permissions (name,description,level,father) VALUES (?,?,?,?)',
                [name, description, level, father],
                function (err, results) {
                    //  响应数据
                    if (err) {
                        res.json({ code: 1, msg: "操作失败", data: { err } })
                    } else {
                        res.json({ code: 0, msg: "添加完成" })
                    }
                    console.log(err + 'ok了!')
                });
        }
    })
    // res.json({ msg: "人员添加", code: 1, data: [] })
})
// 权限（permissions）表操作——删除
router.get('/permissions_delete/:id', (req, res) => {
    console.log(req.params.id)
    db.query('DELETE FROM permissions WHERE id = ?', [parseInt(req.params.id)],
        function (error, result) {
            if (error) {
                res.json({ code: 1, msg: "删除失败", data: { err } })
            } else {
                res.json({ code: 0, msg: "删除成功" })
            }
        }
    )
})
// 权限（permissions）表操作——多个删除
router.get('/permissions_deletes/:id', (req, res) => {
    console.log(req.params.id)
    let userids = req.params.id
    let useridps = JSON.parse(userids)
    let tiaojian = 'DELETE FROM permissions WHERE id IN (?)';
    db.query(tiaojian, [useridps], function (error, result) {
        if (error) {
            res.json({ code: 1, msg: "删除失败", data: { error: error } });
        } else {
            res.json({ code: 0, msg: "删除成功", data: { affectedRows: result.affectedRows } });
        }
    });
})
// 权限（permissions）表操作——查找列表
router.get('/permissions_list', (req, res) => {
    // 获取token
    console.log(req.auth)  //获取token中信息:{ uid: 9, account: '15527098790', iat: 1721979755, exp: 1722238955 }
    let uid = req.auth.uid;
    // 获取url中的参数 ?page=1&page_size=3,参数放在req.query中 { page: '1', page_size: '3' }
    let { page, page_size } = req.query;
    // 查询limit
    let start = (page - 1) * page_size;
    let limit = ` limit ${start}, ${page_size}` //limit 0,3
    let selectSQL = `
    SELECT id,name,description,created_at,updated_at,father,level
    FROM permissions 
    ORDER BY id DESC
    ${limit}`;
    db.query(selectSQL, function (error, results) {
        if (error) console.log(error)
        var id;
        var name;
        var description;
        var created_at;
        var updated_at;
        var level;
        var father;
        let arr = [];
        for (let i = 0; i < results.length; i++) {
            id = results[i].id
            name = results[i].name
            description = results[i].description
            created_at = results[i].account
            updated_at = results[i].updated_at
            father = results[i].father
            level = results[i].level
            arr.push({ id, name, description, created_at, updated_at, father, level })
        }
        //总条数
        db.query("SELECT count(id) as total FROM permissions", (err, data) => {
            console.log("total:", data)
            let totalNum = data[0]?.total
            res.json({ code: 0, msg: "信息详情", data: { list: arr, totalNum } })
        })
    })
})
// 权限（permissions）表操作——查找搜索
router.get("/permissions_search", (req, res) => {
    console.log(req.query);
    let { name, page, page_size } = req.query;

    // 查询limit
    let start = (page - 1) * page_size;
    let limit = ` LIMIT ${start}, ${page_size}`; // limit 0,3

    // 根据搜索的内容不同，生成查询条件
    let whereConditions = ['1 = 1'];
    let queryParams = [];

    if (name) {
        whereConditions.push(`name LIKE ?`);
        queryParams.push(`%${name}%`);
    }

    if (name) {
        whereConditions.push(`description LIKE ?`);
        queryParams.push(`%${name}%`);
    }

    let where = whereConditions.join(' AND ');

    // SQL查询语句（分页查询）
    let selectSQL = `SELECT id, name, description, level, father FROM permissions WHERE ${where} ${limit}`;

    // 计算总数的SQL查询语句
    let countSQL = `SELECT COUNT(*) AS total FROM permissions WHERE ${where}`;

    // 先执行总数查询
    db.query(countSQL, queryParams, function (error, countResults) {
        if (error) {
            console.error(error);
            return res.status(500).json({ code: 1, msg: "数据库查询错误", error: error.message });
        }
        let total = countResults[0].total; // 获取总数

        // 再执行分页查询
        db.query(selectSQL, queryParams, function (error, results) {
            if (error) {
                console.error(error);
                return res.status(500).json({ code: 1, msg: "数据库查询错误", error: error.message });
            }

            let arr = results.map(row => ({
                id: row.id,
                name: row.name,
                description: row.description,
                level: row.level,
                father: row.father
            }));

            // 返回分页数据和总数
            res.json({
                code: 0,
                msg: "搜索详情",
                data: arr,
                total: total
            });
        });
    });
});
// 权限（permissions）表操作——修改-获取数据
router.get('/permissions_users_edit/:id', (req, res) => {
    console.log(req.query, req.params)
    // 、！！！ get 取参数
    //  ?page=1&page_size=3,参数放在请求字符客户，问号开头的，req.query中 { page: '1', page_size: '3' }取
    //  /renyuan/edit/5 ,参数是动态路由 （/edit/:id），req.param中取参数 { id: '5' } 取
    // name, description, created_at, updated_at
    if (!req.params.id) {
        res.send({ code: 1, msg: '缺少参数', data: [] });
    }
    let selectSQL = `
    SELECT id,name,description,created_at,updated_at,level,father
    FROM permissions WHERE id=?
    `;
    db.query(selectSQL, [parseInt(req.params.id)],
        function (error, results) {
            var id;
            var name;
            var description;
            var created_at;
            var updated_at;
            var level;
            var father
            var arr = [];
            for (let i = 0; i < results.length; i++) {
                id = results[i].id
                name = results[i].name
                description = results[i].description
                created_at = results[i].created_at
                updated_at = results[i].updated_at
                level = results[i].level;
                father = results[i].father
                arr.push({ id, name, description, created_at, updated_at, level, father })
            }
            // 响应数据 ,扁平化数组 Array.flat(1)
            res.send({ code: 0, msg: '查询数据', data: arr });
        }
    );
})
// 权限（permissions）表操作——修改-保存数据
router.post('/permissions_save_edit/:id', (req, res) => {
    // 声明body
    let id = req.params.id; //动态路由中的参数通过params取
    let { name, description, level, father } = req.body; //普通提交的数据，在req.body中取到
    // 执行sql语句
    // name, description, level, father
    db.query('UPDATE permissions SET name=?,description=?,level=?,father=? WHERE id=?',
        [name, description, level, father, id], function () {
            // 响应信息
            res.json({ msg: "修改完毕", code: 0, data: { name, description, level, father, id } })
        })
    // res.json({ msg: "人员修改", code: 1, data: [] })
})
// 角色已有的权限
router.get("/have_permissions/:id",(req,res)=>{
    let id = req.params.id;
    db.query("SELECT permission_id FROM rolepermissions WHERE role_id=?",[id],function(error,reslut){
        if(error){
            console.log(error)
            res.status(500).json({ code: 500, msg: "数据库查询错误" });
        }else{
            if(reslut[0]){
                res.json({code:0,msg:"当前角色已经存在权限,请修改！",data:reslut[0]})
            }else{
                res.json({code:1,msg:"当前角色未存在权限,请添加！",data:{}})
            }
            
        }
    })
})
// 权限角色表（rolepermissions）支配
router.post("/permissions_dominate", (req, res) => {
    let { allocation_role, allocations } = req.body;

    // 参数验证
    if (!allocation_role || !allocations) {
        return res.status(400).json({ code: 400, msg: "缺少必要的参数" });
    }

    db.query("SELECT * FROM rolepermissions WHERE role_id=?", [allocation_role], function (error, resultsAll) {
        if (error) {
            console.log(error);
            return res.status(500).json({ code: 500, msg: "数据库查询错误" });
        } else {
            if (resultsAll) {
                // 更新操作
                db.query("UPDATE rolepermissions SET permission_id=? WHERE role_id=?",
                    [String(JSON.parse(allocations)), allocation_role],
                    function (error, results) {
                        if (error) {
                            console.log(error);
                            return res.status(500).json({ code: 500, msg: "更新失败" });
                        } else {
                            return res.json({ code: 0, msg: "此角色已设置权限，已经进行修改！" });
                        }
                    }
                );
            } else {
                // 插入操作
                db.query("INSERT INTO rolepermissions (role_id, permission_id) VALUES (?, ?)",
                    [allocation_role, allocations],
                    function (error, results) {
                        if (error) {
                            console.log(error);
                            return res.status(500).json({ code: 500, msg: "添加失败" });
                        } else {
                            return res.json({ code: 0, msg: "添加完成" });
                        }
                    }
                );
            }
        }
    });
});
// 权限的批量授权
router.post("/permissions_dominate_PL/:id", (req, res) => {
    let id = req.params.id; // 动态路由中的参数通过 params 取
    let { allocation_role, allocations } = req.body;

    db.query("SELECT * FROM rolepermissions WHERE id=?", [id], function (error, results) {
        if (error) {
            // 处理错误情况
            return res.status(500).send({ code: -1, msg: 'Database query failed', error: error });
        }

        if (results.length === 0) {
            // 如果没有找到记录，返回错误
            return res.status(404).send({ code: -1, msg: 'Record not found' });
        }

        // 假设results是一个数组，且只有一个元素，因为id是唯一的
        let record = results[0];
        let permission_id_old = record.permission_id;

        // 检查allocation_role是否为数组
        if (!Array.isArray(allocation_role)) {
            return res.status(400).send({ code: -1, msg: 'allocation_role必须是一个数组' });
        }

        // 遍历allocation_role数组，为每个role_id添加新的permission_id
        allocation_role.forEach(role_id => {
            // 构建更新语句，将allocations添加到对应的role_id的permission_id字段
            // 假设permission_id字段是逗号分隔的字符串
            let newPermissions = (permission_id_old || '') + ',' + allocations;

            // 更新rolepermissions表
            db.query("UPDATE rolepermissions SET permission_id=? WHERE id=? AND role_id=?", [newPermissions, id, role_id], function (error, updateResults) {
                if (error) {
                    // 处理更新错误
                    return res.status(500).send({ code: -1, msg: 'Database update failed', error: error });
                }

                // 检查是否成功更新
                if (updateResults.affectedRows === 0) {
                    // 如果没有行被更新，可能是因为没有找到匹配的记录
                    return res.status(404).send({ code: -1, msg: 'No record updated' });
                }
            });
        });

        // 返回成功响应
        res.json({ code: 0, msg: "批量授权" });
    });
});

// 导出文件——————注意
module.exports = router;